package com.fuliangyun.weather;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.bumptech.glide.Glide;
import com.fuliangyun.weather.gson.Forecast;
import com.fuliangyun.weather.gson.Suggestion;
import com.fuliangyun.weather.gson.Weather;
import com.fuliangyun.weather.utils.HttpUtils;
import com.fuliangyun.weather.utils.Utility;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class WeatherActivity extends AppCompatActivity {

    private ScrollView weatherLayout;
    private TextView titleCity;
    private TextView titleUpdateTime;
    private TextView degreeText;
    private TextView weatherInfoText;
    private LinearLayout forecastLayout;
    private TextView aqiText;
    private TextView pm25Text;
    private TextView comfortText;
    private TextView carWashText;
    private TextView sportText;

    private ImageView bingPicImg;   // 背景图片

    public SwipeRefreshLayout swipeRefreshLayout;  // 手动更新

    public DrawerLayout drawerLayout;
    private Button navButton;   // 返回选择城市

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= 21){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            );
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        setContentView(R.layout.activity_weather);

        // 初始化各种控件
        weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
        titleCity = (TextView) findViewById(R.id.title_city);
        titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
        degreeText = (TextView) findViewById(R.id.degree_text);
        weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
        forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
        aqiText = (TextView) findViewById(R.id.aqi_text);
        pm25Text = (TextView) findViewById(R.id.pm25_text);
        comfortText = (TextView) findViewById(R.id.comfort_text);
        carWashText = (TextView) findViewById(R.id.car_wash_text);
        sportText = (TextView) findViewById(R.id.sport_text);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh); // 手动更新
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); //

        drawerLayout = (DrawerLayout) findViewById(R.id.draw_layout);
        navButton = (Button) findViewById(R.id.nav_button); // 返回选择城市

        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        // 加载背景图片
        bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
        String bingPic = preferences.getString("bing_pic", null);   // 获取缓存图片
        if (bingPic != null && !"".equals(bingPic)){
            // 判断当前是否需要重新获取
            if (isUpdate()){
                // 从服务器获取图片
                loadBingPic();
            }else {
                Glide.with(this).load(bingPic).into(bingPicImg);
            }
        }else {
            // 从服务器获取图片
            loadBingPic();
        }

        String weatherString = preferences.getString("weather", null);
        final String weatherId;   // 天气ID
        if (weatherString != null && !"".equals(weatherString)){
            // 判断当前是否需要重新获取
            if (isUpdate()){
                weatherId = preferences.getString("weather_id", null);
                weatherLayout.setVisibility(View.INVISIBLE);
                requestWeather(weatherId);
            }else {
                Weather weather = Utility.handleWeatherResponse(weatherString);
                weatherId = weather.basic.weatherId;
                showWeatherInfo(weather);
            }
        }else {
            weatherId = getIntent().getStringExtra("weatherId");
            weatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(weatherId);
        }

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeather(weatherId); // 重新加载数据
            }
        });
    }

    /**
     * 根据天气ID请求城市天气信息
     * @param weatherId
     */
    public void requestWeather(final String weatherId){
        String weatherUrl = "https://free-api.heweather.com/s6/weather?location="+weatherId+"&lang=cn&unit=m&key=9a2f283ec28f448289493d421167724c";

        HttpUtils.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_LONG).show();
                swipeRefreshLayout.setRefreshing(false); // 停止刷新
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                final Weather weather = Utility.handleWeatherResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weather != null && "ok".equals(weather.status)){
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather", responseText);
//                            editor.apply();
                            showWeatherInfo(weather);

                            // 缓存请求时间
                            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String dd = df.format(new Date());
                            editor.putString("requestDate", dd);
                            editor.putString("weather_id", weatherId);
                            editor.apply();
                        }else {
                            Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_LONG).show();
                        }
                        swipeRefreshLayout.setRefreshing(false); // 停止刷新
                    }
                });
            }
        });
    }

    private void showWeatherInfo(Weather weather){
        titleCity.setText(weather.basic.cityName);
        titleUpdateTime.setText(weather.update.updateTime);
        degreeText.setText(weather.now.temperature+"℃");
        weatherInfoText.setText(weather.now.condTxt);

        forecastLayout.removeAllViews();
        for (Forecast f: weather.forecastList){
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
            TextView dateText = view.findViewById(R.id.date_text);
            TextView infoText = view.findViewById(R.id.info_text);
            TextView maxText = view.findViewById(R.id.max_text);
            TextView minText = view.findViewById(R.id.min_text);

            dateText.setText(f.date);
            infoText.setText(f.condTxt);
            maxText.setText(f.tmpMax+"℃");
            minText.setText(f.tmpMin+"℃");
            forecastLayout.addView(view);
        }
//        if (weather.aqi != null){
//            aqiText.setText(weather.aqi.);
//        }

        for (Suggestion s: weather.suggestion){
            if ("comf".equals(s.type)){
                comfortText.setText("舒适度："+s.txt);
            }
            if ("sport".equals(s.type)){
                sportText.setText("运动建议："+s.txt);
            }
            if ("cw".equals(s.type)){
                carWashText.setText("洗车指数："+s.txt);
            }
        }
        weatherLayout.setVisibility(View.VISIBLE);
    }

    /**
     * 从服务器获取图片地址
     */
    private void loadBingPic(){

        String add = "http://guolin.tech/api/bing_pic";

        HttpUtils.sendOkHttpRequest(add, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                editor.putString("bing_pic", bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
                    }
                });
            }
        });
    }

    /**
     * 从缓存里面读取时间，判断当前是否需要从服务器重新获取数据
     * 需要更新返回true，否则返回false
     * @return
     */
    private boolean isUpdate(){
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String od = preferences.getString("requestDate", null);
        if (od != null && !"".equals(od)){
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date dd = df.parse(od);
                Date nd = new Date();
                if ((nd.getTime() - dd.getTime()) >= (1000 * 60 *30)){
                    return true;
                }else {
                    return false;
                }
            } catch (ParseException e) {
                return true;
            }
        }else {
            return true;
        }
    }
}
